/*
* Copyright (c) 2008 Matt Giger http://earthbrowser.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
* ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/

var c_wwind_width			= 340;
var c_wwind_height			= 155;
var c_toffset				= 22;
var c_icon_back_alpha		= 0.9;
var c_fcst_back_top			= 87;
var c_icon_back_left		= 4;
var c_icon_back_width		= 44;
var c_icon_back_height		= 63;
var c_icon_spacing			= 48;
var c_icon_left_offset		= 10;
var c_icon_top_offset		= 13;
var c_fcst_top_offset		= 35;
var c_hilo_top_offset		= 47;
var c_flag_width			= 84;
var c_flag_height			= 42;
var c_values_left			= 55;
var c_values_left2			= 160;

var c_daynames				= ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

var c_flag_prefix			= "http://globe.earthbrowser.com/bflags/";
var c_wxicons_prefix		= "http://globe.earthbrowser.com/wxicons/";
var	c_wikipedia_prefix		= 'http://wikipedia.org/wiki/';

/**
* WeatherWind
*
* Show weather features
* 
*/
function WeatherWind(plugin, properties)
{
	var self = this;
	
	// Get into the plugin namespace
	with(plugin)
	{
		self.location = null;
		self.infowind = null;
		
		// add Weather icon skin
		addSkin(new Skin("weather", "wxicons.png", {
			wind:{ x:0, y:0, width:20, height:17 },
			humidity:{ x:20, y:0, width:14, height:18 },
			sunrise:{ x:0, y:20, width:24, height:24 },
			sunset:{ x:24, y:20, width:24, height:24 },
			pressure:{ x:34, y:0, width:16, height:16 },
			visibility:{ x:0, y:44, width:20, height:20 }
		}));

		var _back_dropshadow = [new DropShadowFilter(2, 45, 0, 0.7, 4, 4)];
		
		// Create a draggable input frame
		self.base =	new Frame({
			x:10, y:15, width:c_wwind_width, height:c_wwind_height, visible:false, draggable:true,
			frameRadius:10, frameWidth:1, backColor:0xffffff, backAlpha:0.4
		});
		self.base.setFilters([new DropShadowFilter(3, 45, 1 ,0.75)]);
		
		
		// close button
		self.close = self.base.addPane(
			new Icon({
				skin:'close', x:self.base.getWidth()-18, y:6, binding:BIND_TOP|BIND_RIGHT
			})
		);
		self.close.addListener("onclick", function(e) {
			self.base.setVisible(false);
			self.infowind.dispose();
			self.infowind = null;
		});
		
		
		
		// city name, a click opens the Wikipedia entry
		self.cityName = self.base.addPane(new Label({
			x:0, y:2, bold:true, size:13, color:0x0000af, text:""
		}));
		self.cityName.addListener("onclick", function(e) {
			var name = self.location.getName();
			var cnt = self.location.getCountry();
			if(cnt.getFips().toLowerCase() == 'us')
				name += '%2C_' + self.location.getState().getName();
			else
				name += '%2C_' + cnt.getName();
			self.set_infowind(c_wikipedia_prefix + name);
		});
		
		// state name
		self.stateName = self.base.addPane(new Label({
			x:100, y:2, bold:true, size:13, color:0x0000af, text:""
		}));
		self.stateName.addListener("onclick", function(e) {
			var cnt = self.location.getCountry();
			var state = self.location.getState();
			var sname = state ? state.getName() : '';
			self.set_infowind(c_wikipedia_prefix + sname + (cnt ? ', ' + cnt.getName() : ''));
		});
		
		// country name
		self.countryName = self.base.addPane(new Label({
			x:self.base.getWidth()-44, y:20, useHandCursor:true,
			size:12, bold:true, color:0x0000af, align:"right", text:""
		}));
		self.countryName.addListener("onclick", function(e) {
			self.set_infowind(c_wikipedia_prefix + self.location.getCountry().getName());
		});
		
		// country flag
		// flag images are large, must scale them to fit
		self.countryFlag = self.base.addPane(new Icon({
			x:self.base.getWidth() - c_flag_width - 10, y:40,
			width:c_flag_width, height:c_flag_height, useHandCursor:true,
			binding:BIND_TOP|BIND_RIGHT
		}));
		self.countryFlag.setFilters(_back_dropshadow);
		self.countryFlag.addListener("onload", function(e) {
			var cf = self.countryFlag;
			if(cf.getWidth() > c_flag_width) {
				cf.setWidth(c_flag_width);
				cf.setScaleY(cf.getScaleX());
			}
			if(cf.getHeight() > c_flag_height) {
				cf.setHeight(c_flag_height);
				cf.setScaleX(cf.getScaleY());
			}
			cf.setX(self.base.getWidth() - cf.getWidth() - 10);
		});
		self.countryFlag.addListener("onclick", function(e) {
			self.set_infowind(c_wikipedia_prefix + self.location.getCountry().getName());
		});
		
		// weather icon backdrop
		var wback = self.base.addPane(new Frame({
			x:c_icon_back_left, y:c_toffset,
			width:c_icon_back_width, height:c_icon_back_height, 
			alpha:c_icon_back_alpha, backColor:0
		})).setFilters(_back_dropshadow);
	
		
		// "current"
		self.base.addPane(new Label({
			x:c_icon_back_left-1, y:c_toffset, width:c_icon_back_width-1, height:9,
			size:10, bold:true, color:0xffffff, text:"current",
			fixedWidth:false, binding:BIND_TOP|BIND_LEFT|BIND_RIGHT
		}));
		
		// weather icon
		self.wxicon = self.base.addPane(new Icon({
			x:c_icon_back_left + c_icon_left_offset, y:c_toffset+c_icon_top_offset
		}));

		// current forecast
		self.curfcst = self.base.addPane(new Label({
			x:c_icon_back_left-1, y:c_toffset+c_fcst_top_offset, width:c_icon_back_width, height:10,
			size:10, color:0xffffff, fixedWidth:false, binding:BIND_TOP|BIND_LEFT|BIND_RIGHT
		}));
		
		// temperature
		self.curtemp = self.base.addPane(new Label({
			x:c_icon_back_left-1, y:c_toffset+c_hilo_top_offset, width:c_icon_back_width, height:10,
			size:10, color:0xffffff, fixedWidth:false, binding:BIND_TOP|BIND_LEFT|BIND_RIGHT
		}));
		
		// windspeed and direction
		self.wind = self.base.addPane(new Label({
			x:c_values_left + 22, y:c_toffset, size:12
		}));
		
		// humidity
		self.humidity = self.base.addPane(new Label({
			x:c_values_left + 22, y:c_toffset+23, size:12
		}));
		
		// sunrise
		self.srise = self.base.addPane(new Label({
			x:c_values_left + 22, y:c_toffset+47, size:12
		}));
		
		// pressure
		self.pressure = self.base.addPane(new Label({
			x:c_values_left2 + 22, y:c_toffset, size:12
		}));
		
		// visibility
		self.visib = self.base.addPane(new Label({
			x:c_values_left2 + 22, y:c_toffset+23, size:12
		}));
		
		// sunset
		self.sset = self.base.addPane(new Label({
			x:c_values_left2 + 22, y:c_toffset+47, size:12
		}));
		
		self.base.addPane(new Icon({skin:"weather:wind", x:c_values_left + 1, y:c_toffset}));
		self.base.addPane(new Icon({skin:"weather:humidity", x:c_values_left + 2, y:c_toffset+22}));
		self.base.addPane(new Icon({skin:"weather:sunrise", x:c_values_left + 2, y:c_toffset+39}));
		self.base.addPane(new Icon({skin:"weather:pressure", x:c_values_left2 + 2, y:c_toffset}));
		self.base.addPane(new Icon({skin:"weather:visibility", x:c_values_left2 + 0, y:c_toffset+22}));
		self.base.addPane(new Icon({skin:"weather:sunset", x:c_values_left2 -5, y:c_toffset+39}));
		
		self.icons = [];
		self.daynames = [];
		self.fcst_txt = [];
		self.hilo = [];
		for(var i=0; i<7; ++i)
		{
			var back = self.base.addPane(new Frame({
				x:c_icon_back_left + i*c_icon_spacing, y:c_fcst_back_top,
				width:c_icon_back_width, height:c_icon_back_height, 
				alpha:c_icon_back_alpha, backColor:0
			}));
			back.setFilters(_back_dropshadow);
			
			var icon = self.base.addPane(new Icon({
				x:c_icon_back_left + c_icon_left_offset + i*c_icon_spacing, y:c_fcst_back_top + c_icon_top_offset
			}));
			self.icons.push(icon);
			
			var dname = self.base.addPane(new Label({
				x:c_icon_back_left + i*c_icon_spacing - 1, y:c_fcst_back_top - 2,
				width:c_icon_back_width, height:12,
				size:11, bold:true, color:0xffffff,
				fixedWidth:false, binding:BIND_TOP|BIND_LEFT|BIND_RIGHT
			}));
			self.daynames.push(dname);
			
			var fcst = self.base.addPane(new Label({
				x:c_icon_back_left + i*c_icon_spacing - 1, y:c_fcst_back_top + c_fcst_top_offset,
				size:10, color:0xffffff, fixedWidth:false,
				width:c_icon_back_width, height:10, binding:BIND_TOP|BIND_LEFT|BIND_RIGHT
			}));
			self.fcst_txt.push(fcst);
			
			var hilo = self.base.addPane(new Label({
				x:c_icon_back_left + i*c_icon_spacing - 1, y:c_fcst_back_top + c_hilo_top_offset,
				size:10, color:0xffffff, fixedWidth:false,
				width:c_icon_back_width, height:10, binding:BIND_TOP|BIND_LEFT|BIND_RIGHT
			}));
			self.hilo.push(hilo);
		}
		
		// set the current location
		self.setLocation = function(loc)
		{
			self.location = loc;
			var cnt = loc.getCountry();
			var state = loc.getState();
			
			self.base.setVisible(true);
			
			var st_name = state ? state.getName() : '';
			self.cityName.setText(loc.getName() + (st_name.length > 0 ? ',' : ''));
			self.stateName.setText(st_name);
			
			self.cityName.setX((self.base.getWidth() - self.cityName.getWidth() - self.stateName.getWidth()) * 0.5);
			self.stateName.setX(self.cityName.getX() + self.cityName.getWidth() + 2);
			
			self.countryName.setText(cnt.getName());
			self.countryName.setX(self.base.getWidth() - self.countryName.getWidth() - 10);
			
			var furl = c_flag_prefix + cnt.getFips().toLowerCase() + '.gif';
			if(furl != self.countryFlag.getUrl())
				self.countryFlag.setUrl(furl);
			
			var amf = new AMFConnection('http://api.earthbrowser.com/gateway/');
			amf.addListener('onsuccess', function(e) { self.setWeather(amf.getData()); });
			amf.callFunc('weather.status', loc.getId());	
		};
		
		// set the weather
		self.setWeather = function(wxobj)
		{
			var metric = getViewOptions().getMetric();
			var time24 = getViewOptions().getTime24hr();
			var degree = metric ? '˚C' : '˚F';
			
			var temp = metric ? wxobj.observation.temp : celsius2F(wxobj.observation.temp);
			var wind = metric ? wxobj.observation.wind : wxobj.observation.wind / 1.609
			var wdir = wxobj.observation.wind_dir;
			var pressure = metric ? wxobj.observation.baro_pressure : wxobj.observation.baro_pressure / 33.865;
			var visd = metric ? wxobj.observation.visibility : wxobj.observation.visibility / 1.609;
			var speed_unit = metric ? 'kmph' : 'mi/hr';
			var pressure_unit = metric ? 'hPa' : 'inHg';
			var distance_unit = metric ? 'km' : 'mi';
			
			self.wxicon.setUrl(c_wxicons_prefix + wxobj.observation.icon_id + '.png');
			self.curfcst.setText(wxobj.observation.fcst);
			self.curtemp.setText(Math.floor(temp*10)/10.+degree);
			self.wind.setText((wind > 0) ? (Math.floor(wind) + ' ' + speed_unit + ' ' + wdir) : "calm");
			self.humidity.setText(wxobj.observation.humidity + '%');
			self.pressure.setText(Math.floor(pressure*10)/10 + ' ' + pressure_unit);
			self.visib.setText(Math.floor(visd) + ' ' + distance_unit);
			
			var sunrise = self.location.getSunrise(),sunset = self.location.getSunset();
			self.srise.setText(sunrise ? utc_minute_str(sunrise, time24) : "--");
			self.sset.setText(sunset ? utc_minute_str(sunset, time24) : "--");
			
			var len = wxobj.forecast.length;
			for(var i=0; i<len; ++i)
			{
				var fday = wxobj.forecast[i];
				var idx = fday.day_sequence-1;
				self.icons[idx].setUrl(c_wxicons_prefix + fday.icon + '.png');
				self.daynames[idx].setText(c_daynames[fday.day_of_week-1]);
				self.fcst_txt[idx].setText(fday.fcst);
				
				var high = metric ? fday.high_temp : celsius2F(fday.high_temp);
				var low = metric ? fday.low_temp : celsius2F(fday.low_temp);
				self.hilo[idx].setText(Math.floor(high) + '/' + Math.floor(low) + degree);
				
			}
		};
		
		// create and populate the InfoWindow
		self.set_infowind = function(url)
		{
			if(!self.infowind)
				self.infowind = addPane(new InfoWindow({
					width:220, height:140, frameRadius:20, frameWidth:1, backColor:0xffffff
				}));
			self.infowind.setUrl(url);
			self.infowind.setWidth(plugin.getWidth() * 0.7);
			self.infowind.setHeight(plugin.getHeight() * 0.9);
		};
		
		self.dispose = function()
		{
			
		};
		
	}
	
	return self;
}

/**
*
*/
function celsius2F(temp)
{
	return temp * 1.8 + 32;
}

/**
*
*/
///
function utc_minute_str(date, time24)
{
	var hr = date.getUTCHours();
	var mi = date.getUTCMinutes();
	if(time24)
		return hr + ':' + ((mi < 10) ? '0' + mi : mi);
		
	var pm = (hr >= 12);
	var h = (hr > 12) ? hr - 12 : (hr == 0 ? 12 : hr);
	return h + ':' + ((mi < 10) ? '0' + mi : mi) + (pm ? 'pm' : 'am');
}

